package com.atung.parking.config.permission;

import com.atung.parking.config.auth.AuthUserMangerContext;
import com.atung.parking.config.auth.entity.AuthUserEntity;
import com.atung.parking.config.exception.PermissionValidException;
import com.atung.parking.enums.AdminType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


import java.util.Arrays;

/**
 * @author Administrator
 */
@Aspect
@Component
@Slf4j
public class PermissionValidAspect {
    @Pointcut("@annotation(PermissionValid)")
    public void permissionValidHandel(PermissionValid PermissionValid) {
    }

    @Before("permissionValidHandel(PermissionValid)")
    public void PermissionValidVerify(JoinPoint joinPoint, PermissionValid PermissionValid) {
        AdminType[] roleType = PermissionValid.roleType();
        String PermissionValidName = PermissionValid.permissionValue();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new PermissionValidException();
        }
        AuthUserEntity authUserEntity = AuthUserMangerContext.getAuthUserEntity();
        if (!Arrays.asList(roleType).contains(authUserEntity.getRoleType())) {
            //暂无权限
            throw new PermissionValidException();
        }
        if (StringUtils.hasText(PermissionValidName)) {
            if (!authUserEntity.getPermissionValid().contains(PermissionValidName)) {

                throw new PermissionValidException();
                //暂无权限
            }
        }
    }
}
